﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;

namespace DAO
{
    public class sqlDataAccessHelper
    {
        private static SqlConnection connect;
        protected static string strconnect = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
        public static string ConnectionString
        {
            get
            {
                return strconnect;
            }
        }
               
        public sqlDataAccessHelper()
        {
            connect = new SqlConnection(strconnect);
        }

        #region Mở dữ liệu
        public bool Open()
        {
            try
            {
                //Khởi động connection
                connect = new SqlConnection(strconnect);
                connect.Open();
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region Đóng dữ liệu
        public void Close()
        {
            if (connect != null)
            {
                if (connect.State == ConnectionState.Open)
                    connect.Close();
            }
        }
        #endregion

        #region Kết nối dữ liệu
        public DataTable ExecuteQuery(string sql)
        {
            Open();
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(sql, connect);
            da.Fill(ds);
            Close();
            return ds.Tables[0];
        }
        #endregion

        #region Thêm, xóa, sửa không cần trả về bảng
        public int ExecuteNonQuery(string sql)
        {
            int n = -1;
            try
            {
                Open();
                SqlCommand command = new SqlCommand(sql, connect);
                n = command.ExecuteNonQuery();
                Close();
            }
            catch(Exception ex)
            {
                throw ex;
            }           
           
            return n;
        }
        #endregion 

    }
    
}

